package dayu.filter;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author dayu
 * @create 2018/12/13 15:53
 * @Description 自定义角色认证过滤器,自定义过滤规则roles表示任意一个role存在就表示认证成功
 */
public class CustomRolesAuthorizationFilter  extends AuthorizationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;

        if (rolesArray == null || rolesArray.length == 0) {
            return true;
        }

        for (String role : rolesArray) {
            if(subject.hasRole(role)){
                return true;
            }
        }
        return false;
    }
}
